/**
 * @Author: 安广伟
 * @Email: anguangwei@jwzh.tech
 * @Date: 2024-09-09 15:16:39
 * @LastEditTime 2024-09-09 15:16:39
 * @since: 1.0.0
 * @Version: 1.0.0
 * @Description:
 */

package com.ry.mall.server.config;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import com.ry.mall.server.controller.TokenTimeOutException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.Date;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 这是一个全局错误处理器类。@ExceptionHandler 注解表示这个方法处理所有的 Exception
     * 类型的异常。在这个方法中，我们将异常信息返回给浏览器端，并设置 HTTP 状态码为 500。
     */

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSize;

    @ExceptionHandler(Exception.class)

    public ResponseEntity<String> handleException(Throwable e) {
        log.debug("接管 excpetion，定制返回的内容", e);
        ExceptionObject exceptionObject = new ExceptionObject();
        if (null == e.getCause()) {
            exceptionObject.message = e.getLocalizedMessage();
        } else {
            exceptionObject.message = e.getCause().getLocalizedMessage();
        }

        exceptionObject.error = HttpStatus.INTERNAL_SERVER_ERROR.value();
        exceptionObject.time = new Date();
        // exceptionObject.trace = e.getStackTrace();
        exceptionObject.trace = null;
        if (e instanceof MaxUploadSizeExceededException) {
            exceptionObject.message = "上传文件的字节数，已经超过系统限制的" + maxFileSize + "字节了！";
        }
            if (e instanceof TokenTimeOutException) {
                // 这里特殊化处理
                // session失效的错误指定为 508
                exceptionObject.error = 508;
                exceptionObject.message = e.getMessage();
                return ResponseEntity.status(508).contentType(MediaType.APPLICATION_JSON)
                        .body(JSONObject.toJSONString(exceptionObject));
            }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
                .body(JSONObject.toJSONString(exceptionObject));
    }

    @Data
    private class ExceptionObject {
        @JSONField
        int error;
        @JSONField
        String message;
        @JSONField
        Date time;
        @JSONField
        StackTraceElement[] trace;
        @JSONField
        String path;
    }

}
